package com.song.luence;

import com.song.bean.Article;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;

import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.queryparser.surround.parser.ParseException;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class LuenceTest {

    public void addIndex() {
        File dataDir = new File("");   //数据文件目录
        File indexDir = new File("");  //索引库所在位置

        File[] files = dataDir.listFiles();

        Analyzer luenceAnalyzer = new StandardAnalyzer();  //分词器
        /*try {
            //IndexWriter indexWriter = new IndexWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }*/


    }

    @Test
    public void add() {
        Article article = new Article();

        article.setId(1);
        article.setTitle("Luence 全文检索");
        article.setContent("Lucene是apache软件基金会4 jakarta项目组的一个子项目，" +
                "是一个开放源代码的全文检索引擎工具包，但它不是一个完整的全文检索引擎，而是一个全文检索引擎的架构，" +
                "提供了完整的查询引擎和索引引擎，部分文本分析引擎（英文与德文两种西方语言）。");

        Analyzer analyzer = new StandardAnalyzer();
        Path path = Paths.get("F:\\SONG_WORKSPACE\\IDEA_WORKSPACE\\luence-core\\");  //储存索引文件位置
        try {
            Directory directory = FSDirectory.open(path);
            IndexWriterConfig config = new IndexWriterConfig(analyzer);
            config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

            IndexWriter indexWriter = new IndexWriter(directory, config);
            Document document = new Document();
            document.add(new TextField("id", article.getId().toString(), Field.Store.YES));
            document.add(new TextField("title", article.getTitle(), Field.Store.YES));
            document.add(new TextField("content", article.getContent(), Field.Store.YES));
            indexWriter.addDocument(document);
            indexWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //文件
    @Test
    public void addFile() throws IOException {

        final Path path = Paths.get("F:\\SONG_WORKSPACE\\IDEA_WORKSPACE\\luence-data");

        Directory directory = FSDirectory.open(path);
        Analyzer analyzer = new StandardAnalyzer();

        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
        indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

        IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
        BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("F:\\SONG_WORKSPACE\\IDEA_WORKSPACE\\2017_10_17.stderrout.log")));
        String content = "";
        while ((content = bufferedReader.readLine()) != null) {
            System.out.println(content);
            Document document = new Document();
            document.add(new TextField("logs", content, Field.Store.YES));
            indexWriter.addDocument(document);
        }
        indexWriter.close();
    }


    @Test
    public void SearchFiles() throws IOException, ParseException, Exception {
        //String queryString = "全文检索";
        String queryString = "error";

        //多条件
//        Query q = MultiFieldQueryParser.parse(new String[]{},new String[]{},new StandardAnalyzer());

        final Path path = Paths.get("F:\\SONG_WORKSPACE\\IDEA_WORKSPACE\\luence-core\\");
        Directory directory = FSDirectory.open(path);

        Analyzer analyzer = new StandardAnalyzer();
        IndexReader indexReader = DirectoryReader.open(directory);
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        //单条件
        /*QueryParser queryParser = new QueryParser("log", analyzer);
        Query query = queryParser.parse(queryString);*/

       Query query = new TermQuery(new Term("content","引擎"));

        TopDocs topDocs = indexSearcher.search(query, 10);

        long conut = topDocs.totalHits;
        System.out.println("检索总条数：" + conut);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            Document document = indexSearcher.doc(scoreDoc.doc);
            System.out.print("相关度：" + scoreDoc.score + "-----time:" + document.get("time"));
            System.out.println(document.get("logs"));
        }
    }

}
